<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>栈的封装和使用</title>
</head>

<body>
    <script>
        function Stack() {

            this.items = [];
            // 添加push方法---入栈
            Stack.prototype.push = function (element) {
                this.items.push(element)
            }

            // 添加pop方法 ----出栈
            Stack.prototype.pop = function () {
                return this.items.pop()
            }

            // 添加peek方法 --- 返回栈顶元素-不做修改
            Stack.prototype.peek = function () {
                return this.items[this.items.length - 1]
            }

            // isEmpty()判断栈中元素是否为空
            Stack.prototype.isEmpty = function () {
                return this.items.length === 0
            }

            // size()获取栈中元素的个数
            Stack.prototype.size = function () {
                return this.items.length
            }

            // toString()--以字符串形式输出栈内数据
            Stack.prototype.toString = function () {
                let resultString = '';
                // for (i = 0; i < this.items.length; i++) {
                //     resultString += this.items[i] + ' '
                // }
                for (let i of this.items) {
                    resultString += i + ' '
                }
                return resultString
            }

        }

        var S = new Stack();
        S.push(10);
        S.push(20);
        S.push(30);
        S.push(40);
        console.log(S);   // items: Array(4) [10, 20, 30, 40]
        console.log(S.pop())  // 40  删除-栈顶元素40
        console.log(S.peek()) // 30  栈顶元素30
        console.log(S.isEmpty())  // false --- 栈中元素不为空
        console.log(S.size())   // 3   -- -剩下了3个元素
        console.log(S.toString())  // 10 20 30



    </script>
</body>

</html>